package rest;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;

import services.book.BookService;
import books.Author;
import books.Category;
import books.Publisher;
import builders.AuthorBuilder;
import builders.BookInfoBuilder;
import dtos.BookInfoDTO;

/**
 */

@Path("/books")
public class BooksRest {

    @Autowired
    private BookService bookService;

    public void setBookService(final BookService bookService) {
        this.bookService = bookService;
    }

    public BookService getBookService() {
        return this.bookService;
    }

    @GET
    @Path("/findall")
    @Produces("application/json")
    public List<BookInfoDTO> findAllBooks() {
        return this.getBookService().getAllBooksDTO();
    }

    @POST
    @Path("/newbook")
    @Produces("application/xml")
    public String addBook(@FormParam("title") final String title, @FormParam("desc") final String desc,
            @FormParam("isbn") final String isbn, @FormParam("author") final List<String> authors,
            @FormParam("cat") final List<String> cats, @FormParam("pub") final String publisher) {

        List<Author> authorsList = new ArrayList<Author>();
        for (String author : authors) {
            authorsList.add(new AuthorBuilder().withName(author).build());
        }
        List<Category> categories = new ArrayList<Category>();
        for (String cat : cats) {
            categories.add(Category.valueOf(cat));
        }

        BookInfoBuilder builder = new BookInfoBuilder();
        builder.withAvailability(true).withTitle(title).withDescription(desc).withAuthors(authorsList)
                .withCategories(categories).withDescription(desc).withIsbn(isbn)
                .withPublisher(new Publisher(publisher)).withRegistration(DateTime.now());

        this.getBookService().addBookInfo(builder.build());

        return "libro: " + builder.build().toString() + " agregado";
    }
}
